//
//  QSCardCycleView.m
//  MyTest
//
//  Created by Song on 2017/9/12.
//  Copyright © 2017年 Song. All rights reserved.
//

#import "QSCardCycleView.h"
#import "QSCardCycleViewLayout.h"
#import "QSCardCycleViewCell.h"
#import "QSCardCycleViewTextCell.h"
#import "QSCustomPageControl.h"

#import "QSCardCycleModel.h"
#import "QSCustomPageModel.h"

#define offsetXCell (self.qs_width - self.itemSize.width) / 2
#define offsetYCell (self.qs_height - self.itemSize.height) / 2

@interface QSCardCycleView()<UICollectionViewDelegate,
                             UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) QSCardCycleViewLayout *layout;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, weak) QSCustomPageControl *pageControl;
@property (nonatomic, strong) QSCardCycleModel *defaultCardCycleModel;
@end

static NSString *const CardCycleViewCellID = @"CardCycleViewCellID";
static NSString *const CardCycleViewTextCellID = @"CardCycleViewTextCellID";

@implementation QSCardCycleView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 初始化默认数据
        [self setupDefaultData];
        // 初始化CollectionView
        [self setupCollectionView];
    }
    
    return self;
}

/**
 *  重写layoutSubviews方法
 */
- (void)layoutSubviews{
    [super layoutSubviews];
    
    [_pageControl setFrame:(CGRect){{0,self.qs_height - 30},{self.qs_width,30}}];
}

/**
 *  初始化默认数据
 */
- (void)setupDefaultData{
    
    _defaultCardCycleModel = [[QSCardCycleModel alloc] init];
    
    /**
     *  定时器
     */
    _defaultCardCycleModel.isTimerRun = NO;
    _defaultCardCycleModel.timeInterval = 1.5f;
    
    /**
     *  pageControl
     */
    _defaultCardCycleModel.pageControlImgArr = nil;
    _defaultCardCycleModel.isNeedPageControl = NO;
    _defaultCardCycleModel.selectedColor = [UIColor greenColor];
    _defaultCardCycleModel.unselectedColor = [UIColor whiteColor];
    _defaultCardCycleModel.pageControlStyle = QSPageControlStyleMiddle;
}

/**
 *  初始化 PageControl
 */
- (void)setupPageControl{
    if(_pageControl) return;
    
    if(_imageArr.count == 1){
        [_pageControl setHidden:YES];
        return;
    }
    
    QSCustomPageControl *pageControl = [[QSCustomPageControl alloc] init];
    pageControl.frame = CGRectMake(0, self.qs_height - 30, kScreenWidth, 30);
    [pageControl setNumberOfPages:self.imageArr.count];
    _pageControl = pageControl;
    
    QSCustomPageModel *model = [[QSCustomPageModel alloc] init];
    model.pointWidth = 6;
    model.pointHeight = 6;
    model.pointSpacing = 8;
    model.scale = self.cardCycleModel.scale > 0.0 ? self.cardCycleModel.scale : 1.0;
    model.isEllipse = self.cardCycleModel.isEllipse;
    model.pageControlLocation = (QSPageControlLocation)self.cardCycleModel.pageControlStyle;
    model.currentColor = self.cardCycleModel.selectedColor;
    model.otherColor = self.cardCycleModel.unselectedColor;
    pageControl.pageModel = model;
    
    [self addSubview:pageControl];
}

/**
 *  初始化CollectionView
 */
- (void)setupCollectionView
{
    QSCardCycleViewLayout *layout = [[QSCardCycleViewLayout alloc] init];
    self.layout = layout;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    [self addSubview:collectionView];
    self.collectionView = collectionView;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(0.0);
    }];
    [collectionView.superview layoutIfNeeded];
    
    // 设置背景颜色
    [collectionView setBackgroundColor:[UIColor whiteColor]];
    // 分页
    [collectionView setPagingEnabled:NO];
    
    // 设置代理
    [collectionView setDelegate:self];
    [collectionView setDataSource:self];
    
    // 隐藏滚动条
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;

    // 注册
    [collectionView registerClass:[QSCardCycleViewCell class] forCellWithReuseIdentifier:CardCycleViewCellID];
    [collectionView registerClass:[QSCardCycleViewTextCell class] forCellWithReuseIdentifier:CardCycleViewTextCellID];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArr.count == 1 ? 1 : self.imageArr.count * 50;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isOnlyDisplayText) {
        QSCardCycleViewTextCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CardCycleViewTextCellID forIndexPath:indexPath];
        NSInteger row = indexPath.row % self.textArr.count;
        cell.title = self.textArr[row];
        
        return cell;
    }
    QSCardCycleViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CardCycleViewCellID forIndexPath:indexPath];
    
    NSInteger row = indexPath.row % self.imageArr.count;
    cell.imageName = self.imageArr[row];
    cell.placeHolderImg = self.placeHolderImg;
    cell.cornerAngle = self.cornerAngle;
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.delegate respondsToSelector:@selector(cardCycleView:didSelectedImageItemAtIndex:)]) {
        NSInteger index = indexPath.row % self.imageArr.count;
        [self.delegate cardCycleView:self didSelectedImageItemAtIndex:index];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self setupTimer];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
        // 判断是否是第一个或最后一个item
        NSInteger index = (scrollView.contentOffset.y + offsetYCell) / self.itemSize.height;
        if (index == _imageArr.count * 50 || index == 0) {
            index = _imageArr.count * 50 * 0.5;
            CGFloat offset = self.itemSize.height * _imageArr.count * 50 * 0.5 - offsetYCell;
            [self.collectionView setContentOffset:CGPointMake(0 , offset) animated:NO];
        }
        
        // 设置PageControl
        if (self.cardCycleModel.isNeedPageControl) {
            CGFloat y = scrollView.contentOffset.y;
            NSString *contentOffSetY = [NSString stringWithFormat:@"%f",(y + offsetYCell + self.itemSize.height) / self.itemSize.height];
            if([[contentOffSetY substringWithRange:NSMakeRange(contentOffSetY.length - 6, 6)] isEqualToString:@"000000"]){
                NSInteger index = ([contentOffSetY integerValue] - 1) % [self.imageArr count];
                [_pageControl setCurrentPage:index];
            }
        }
    } else {
        // 判断是否是第一个或最后一个item
        NSInteger index = (scrollView.contentOffset.x + offsetXCell) / self.itemSize.width;
        if (index == _imageArr.count * 50 || index == 0) {
            index = _imageArr.count * 50 * 0.5;
            CGFloat offset = self.itemSize.width * _imageArr.count * 50 * 0.5 - offsetXCell;
            [self.collectionView setContentOffset:CGPointMake(offset , 0) animated:NO];
        }
        
        // 设置PageControl
        if (self.cardCycleModel.isNeedPageControl) {
            CGFloat x = scrollView.contentOffset.x;
            NSString *contentOffSetX = [NSString stringWithFormat:@"%f",(x + offsetXCell + self.itemSize.width ) / self.itemSize.width];
            if([[contentOffSetX substringWithRange:NSMakeRange(contentOffSetX.length - 6, 6)] isEqualToString:@"000000"]){
                if ([self.imageArr count] > 0) {
                    NSInteger index = ([contentOffSetX integerValue] - 1) % [self.imageArr count];
                    [_pageControl setCurrentPage:index];
                }
            }
        }
    }
}

/**
 *  设置定时器
 */
- (void)setupTimer{
    if([_imageArr count] == 1) return;
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:_cardCycleModel.timeInterval target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    self.timer = timer;
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeTimer{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)timerRun{
    if (self.cardCycleModel.isHorseRaceLamp) {
        if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
            if (_imageArr.count > 0) {
                NSInteger index = (_collectionView.contentOffset.y + offsetYCell) / self.itemSize.height;
                if ((index * _layout.itemSize.height - _imageArr.count * 48 * _layout.itemSize.height < 0.0001) && (index / _imageArr.count > 25)) {
                    CGFloat offset = _layout.itemSize.height * _imageArr.count * 50 * 0.5 - offsetYCell;
                    [self.collectionView setContentOffset:CGPointMake(0, offset) animated:NO];
                }
                CGFloat offset = _collectionView.contentOffset.y + 20;
                [self.collectionView setContentOffset:CGPointMake(0, offset) animated:YES];
            }
        } else {
            if (_imageArr.count > 0) {
                NSInteger index = (_collectionView.contentOffset.x + offsetXCell) / self.itemSize.width;
                if ((index * _layout.itemSize.width - _imageArr.count * 48 * _layout.itemSize.width < 0.0001) && (index / _imageArr.count > 25)) {
                    CGFloat offset = _layout.itemSize.width * _imageArr.count * 50 * 0.5 - offsetXCell;
                    [self.collectionView setContentOffset:CGPointMake(offset, 0) animated:NO];
                }
                CGFloat offset = _collectionView.contentOffset.x + 20;
                [self.collectionView setContentOffset:CGPointMake(offset, 0) animated:YES];
            }
        }
        
        return;
    }
    
    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
        // 判断是否是第一个或最后一个item
        NSInteger index = (_collectionView.contentOffset.y + offsetYCell) / self.itemSize.height;
        if (index == _imageArr.count * 50 || index == 0) {
            index = _imageArr.count * 50 * 0.5;
            CGFloat offset = self.itemSize.height * _imageArr.count * 50 * 0.5 - offsetYCell;
            [self.collectionView setContentOffset:CGPointMake(0, offset) animated:NO];
        }
        
        // 调整偏移量
        CGFloat offset = _collectionView.contentOffset.y + _layout.itemSize.height;
        if (fmod(ABS((offset + offsetYCell)), ABS(_layout.itemSize.height)) == ABS(_layout.itemSize.height)) {
            
            [_collectionView setContentOffset:CGPointMake(0, _collectionView.contentOffset.y + _layout.itemSize.height) animated:YES];
        }else{
            
            NSInteger index = ABS((offset + offsetYCell)) / ABS(_layout.itemSize.height);
            [_collectionView setContentOffset:CGPointMake(0, _layout.itemSize.height * index - offsetYCell) animated:YES];
        }
    } else {
        // 判断是否是第一个或最后一个item
        NSInteger index = (_collectionView.contentOffset.x + offsetXCell) / self.itemSize.width;
        if (index == _imageArr.count * 50 || index == 0) {
            index = _imageArr.count * 50 * 0.5;
            CGFloat offset = self.itemSize.width * _imageArr.count * 50 * 0.5 - offsetXCell;
            [self.collectionView setContentOffset:CGPointMake(offset , 0) animated:NO];
        }
        
        // 调整偏移量
        CGFloat offset = _collectionView.contentOffset.x + _layout.itemSize.width;
        if (fmod(ABS((offset + offsetXCell)), ABS(_layout.itemSize.width)) == ABS(_layout.itemSize.width)) {
            
            [_collectionView setContentOffset:CGPointMake(_collectionView.contentOffset.x + _layout.itemSize.width, 0) animated:YES];
        }else{
            
            NSInteger index = ABS((offset + offsetXCell)) / ABS(_layout.itemSize.width);
            [_collectionView setContentOffset:CGPointMake(_layout.itemSize.width * index - offsetXCell, 0) animated:YES];
        }
    }
}

/**
 *  当子视图从本视图移除时调用
 */
- (void)willRemoveSubview:(UIView *)subview{
    if (!subview) {
        [self removeTimer];
    }
}

#pragma mark - set
- (void)setCardCycleModel:(QSCardCycleModel *)cardCycleModel
{
    _cardCycleModel = cardCycleModel;
    
    /**
     *  定时器
     */
    if(!cardCycleModel.isTimerRun){ // 不需要定时器
        _cardCycleModel.timeInterval = 0.0;
    }else{ // 需要定时器
        if(cardCycleModel.timeInterval <= 0){
            _cardCycleModel.timeInterval = _defaultCardCycleModel.timeInterval;
        }
    }
    
    // 删除定时器
    [self removeTimer];
    // 设置定时器
    if(cardCycleModel.isTimerRun) [self setupTimer];
    
    /**
     *  pageControl
     */
    if(![cardCycleModel pageControlStyle])
        _cardCycleModel.pageControlStyle = _defaultCardCycleModel.pageControlStyle;
    
    if(![cardCycleModel selectedColor])
        _cardCycleModel.selectedColor = _defaultCardCycleModel.selectedColor;
    
    if(![cardCycleModel unselectedColor])
        _cardCycleModel.unselectedColor = _defaultCardCycleModel.unselectedColor;
}

- (void)setItemSize:(CGSize)itemSize
{
    _itemSize = itemSize;
    self.layout.itemSize = itemSize;
}

- (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection
{
    _scrollDirection = scrollDirection;
    self.layout.scrollDirection = scrollDirection;
}

- (void)setVisibleCount:(NSInteger)visibleCount
{
    _visibleCount = visibleCount;
    self.layout.visibleCount = visibleCount;
}

- (void)setIsCardStytle:(BOOL)isCardStytle
{
    _isCardStytle = isCardStytle;
    self.layout.isCardStytle = isCardStytle;
}

- (void)setIsOnlyHorizontalScale:(BOOL)isOnlyHorizontalScale
{
    _isOnlyHorizontalScale = isOnlyHorizontalScale;
    self.layout.isOnlyHorizontalScale = isOnlyHorizontalScale;
}

- (void)setImageArr:(NSArray *)imageArr
{
    _imageArr = imageArr;
    [self jumpToLocation];
    
    if (self.cardCycleModel.isNeedPageControl) {
        // 初始化PageControl
        [self setupPageControl];
    }
    
    [self.collectionView reloadData];
}

- (void)setTextArr:(NSArray *)textArr
{
    _textArr = textArr;
    
    self.imageArr = textArr;
}

/**
 *  跳转到collectionView的某个位置
 */
- (void)jumpToLocation{
    if(_imageArr.count == 1) return;
    
    [self.collectionView.superview layoutIfNeeded];
    CGFloat offset = self.itemSize.width * _imageArr.count * 50 * 0.5 - offsetXCell;
    [self.collectionView setContentOffset:CGPointMake(offset , 0) animated:NO];
}

/****************************** == 判断 数组是否为空 == ********************************/
+ (BOOL)isEmptyArray:(NSArray *)array{
    return [[self alloc] isEmptyArray:array];
}

- (BOOL)isEmptyArray:(NSArray *)array{
    if(array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0){
        return YES;
    }
    return NO;
}
@end
